package com.bibrApp.difu.actvity.certificate_mvp;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.R;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.base.BasePermissionActivity;
import com.bibrApp.difu.utils.CheckUtils;
import com.bibrApp.difu.utils.FileUtils;
import com.bibrApp.difu.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.barlibrary.ImmersionBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class CertificateActivity extends BasePermissionActivity<CertificatePresenter> implements ICertificateView, TextWatcher, View.OnFocusChangeListener {

    private ImmersionBar mImmersionBar;
    private Context mContext;
    @BindView(R.id.certificate_uid_tv)
    TextView certificate_uid_tv;
    @BindView(R.id.id_card_name_et)
    EditText id_card_name_et;
    @BindView(R.id.id_card_num_et)
    EditText id_card_num_et;
    @BindView(R.id.high_cert_id_card_up_iv)
    ImageView upIV;
    @BindView(R.id.high_cert_id_card_down_iv)
    ImageView downIV;
    @BindView(R.id.high_cert_hand_id_card_iv)
    ImageView handIV;
    @BindView(R.id.high_cert_sure_btn)
    Button high_cert_sure_btn;

    @Override
    protected void initPresenter() {
        presenter = new CertificatePresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_high_certificate;
    }

    @Override
    public void initView() {
        mContext = this;
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();

        DfApp dfApp = (DfApp) getApplication();
        if(!TextUtils.isEmpty(dfApp.getuId())){
            certificate_uid_tv.setText(dfApp.getuId());
        }
        id_card_name_et.addTextChangedListener(this);
        id_card_num_et.addTextChangedListener(this);
        id_card_name_et.setOnFocusChangeListener(this);
        id_card_num_et.setOnFocusChangeListener(this);
    }


    @Override
    public void error(String msg) {
        ToastUtils.ShowToast(mContext, msg);
    }

    @Override
    public void success(String msg) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }

    }

    @OnClick(R.id.high_cert_id_card_up_iv)
    public void onClickIdCardUp() {
        reqPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, () -> choosePhoto(RC_CHOOSE_PHOTO_UP));
    }

    @OnClick(R.id.high_cert_id_card_down_iv)
    public void onClickIdCardDown() {
        reqPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, () -> choosePhoto(RC_CHOOSE_PHOTO_DOWN));
    }

    @OnClick(R.id.high_cert_hand_id_card_iv)
    public void onClickIdCardHand() {
        reqPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, () -> choosePhoto(RC_CHOOSE_PHOTO_HAND));
    }

    @OnClick(R.id.high_cert_sure_btn)
    public void onClickUpLoadPic() {
        upLoadPic();
    }

    private void upLoadPic() {
        File fileUp;
        File fileDown;
        File fileHand;
        if (filePathUp != null && filePathDown != null && filePathHand != null) {
            try {
                fileUp = FileUtils.getFileFromUri(filePathUp, mContext);
                fileDown = FileUtils.getFileFromUri(filePathDown, mContext);
                fileHand = FileUtils.getFileFromUri(filePathHand, mContext);
                List<MultipartBody.Part> images = new ArrayList<>();
                //图片压缩到3M以内
                File compressFileUp = FileUtils.compressImage(mContext,fileUp.getAbsolutePath() ,3);
                File compressFileDown= FileUtils.compressImage(mContext,fileDown.getAbsolutePath() ,3);
                File compressFileHand = FileUtils.compressImage(mContext,fileHand.getAbsolutePath() ,3);
                RequestBody fileBodyUp = RequestBody.create(MediaType.parse("image/png"), compressFileUp);
                RequestBody fileBodyDown = RequestBody.create(MediaType.parse("image/png"), compressFileDown);
                RequestBody fileBodyHand = RequestBody.create(MediaType.parse("image/png"), compressFileHand);

                MultipartBody.Part partUp = MultipartBody.Part.createFormData("idcardPicFront", "idcardPicFront", fileBodyUp);
                MultipartBody.Part partDown = MultipartBody.Part.createFormData("idcardPicBack", "idcardPicBack", fileBodyDown);
                MultipartBody.Part partHand = MultipartBody.Part.createFormData("idcardPicOnhand", "idcardPicOnhand", fileBodyHand);
                images.add(partUp);
                images.add(partDown);
                images.add(partHand);
                presenter.highCert(images);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtils.ShowToast(mContext, "请先选择上传对应的图");
        }

    }

    public static final int RC_CHOOSE_PHOTO_UP = 2001;
    public static final int RC_CHOOSE_PHOTO_DOWN = 3001;
    public static final int RC_CHOOSE_PHOTO_HAND = 4001;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String name = id_card_name_et.getText().toString().replaceAll(" ","");
        String num = id_card_num_et.getText().toString().replaceAll(" ","");
        if (!TextUtils.isEmpty(num) && !TextUtils.isEmpty(name)) {
            high_cert_sure_btn.setEnabled(true);
            high_cert_sure_btn.setClickable(true);
        } else {
            high_cert_sure_btn.setEnabled(false);
            high_cert_sure_btn.setClickable(false);
        }
    }
    /**
     * 分发点击除 EditText 外区域，当前焦点在 ET 上，EditText 取消焦点
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        View v = getCurrentFocus();
        if (v != null && v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(event);
    }
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String name = id_card_name_et.getText().toString().replaceAll(" ", "");
        String num = id_card_num_et.getText().toString().replaceAll(" ", "");
        switch (v.getId()) {
            case R.id.id_card_name_et:
                if (!hasFocus) {
                    if (!TextUtils.isEmpty(name)) {
                        if(!TextUtils.isEmpty(num) && CheckUtils.isIDNumber(num)){
                            presenter.ordinaryCert(name,num);
                        }else{
                            ToastUtils.ShowToast(mContext,"请输入正确的身份证号码");
                        }
                    } else {
                        ToastUtils.ShowToast(mContext,"姓名不能为空");
                    }
                }
                break;
            case R.id.id_card_num_et:
                if (!hasFocus) {
                    if (!TextUtils.isEmpty(num)) {
                        if (CheckUtils.isIDNumber(num)) {
                            if(!TextUtils.isEmpty(name)){
                                presenter.ordinaryCert(name,num);
                            }
                        } else {
                            ToastUtils.ShowToast(mContext,"请输入正确的身份证号码");
                        }
                    }else{
                        ToastUtils.ShowToast(mContext,"请输入身份证号码");
                    }
                }
                break;
            default:
                break;
        }

    }
    private void choosePhoto(int RequestCode) {
        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, RequestCode);
    }

    private Uri filePathUp;
    private Uri filePathDown;
    private Uri filePathHand;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || data.getData() == null) {
            return;
        }
        Uri uri = data.getData();
        String filePath = null;
        if (uri != null) {
            filePath = FileUtils.getFilePathByUri(this, uri);
        }

        switch (requestCode) {

            case RC_CHOOSE_PHOTO_UP:

                if (!TextUtils.isEmpty(filePath)) {
                    filePathUp = uri;
                    RequestOptions requestOptions1 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
                    //将照片显示在 ivImage上
                    Glide.with(this).load(filePath).apply(requestOptions1).into(upIV);
                }
                break;
            case RC_CHOOSE_PHOTO_DOWN:
                if (!TextUtils.isEmpty(filePath)) {
                    filePathDown = uri;
                    RequestOptions requestOptions1 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
                    //将照片显示在 ivImage上
                    Glide.with(this).load(filePath).apply(requestOptions1).into(downIV);
                }
                break;
            case RC_CHOOSE_PHOTO_HAND:
                if (!TextUtils.isEmpty(filePath)) {
                    filePathHand = uri;
                    RequestOptions requestOptions2 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
                    //将照片显示在 ivImage上
                    Glide.with(this).load(filePath).apply(requestOptions2).into(handIV);
                }
                break;
            default:
                break;
        }
    }
}
